/**
 * made in 2007-11-14上午08:01:28
 * 唉 你丫真二 
 */
package com.litxuf.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.litxuf.logic.core.ManagerFactory;

/**
 * @author xufeng
 * 
 */
public class FileUploadServlet extends HttpServlet {
	private static final Logger logger = Logger
			.getLogger(FileUploadServlet.class.getName());

	private static final long serialVersionUID = 1L;

	private static String path = "";

	private static String url = "";

	private static String allowedExtensions = "";

	public void init() throws ServletException {

		path = getInitParameter("path");
		url = getInitParameter("url");
		allowedExtensions = getInitParameter("allowedExtensions");
		if (url == null){
			url = "";
			
		}
		if (path == null){
			path = "";
			
		}
		System.out.println("--> path="+path);
		String realBaseDir = getServletContext().getRealPath(path);
		System.out.println("--> allowedExtensions="+allowedExtensions);
		System.out.println("---> realBaseDir="+realBaseDir);
		File baseFile = new File(realBaseDir);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html; charset=utf-8");
		response.setHeader("Cache-Control", "no-cache");
		PrintWriter out = response.getWriter();
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		List list;
		String fileName = "";
		String realBaseDir = getServletContext().getRealPath(path);
		System.out.println("path::"+ realBaseDir);
		java.text.SimpleDateFormat isNow = new java.text.SimpleDateFormat(
		"yyyyMMddHHmmss");
		try {
			list = upload.parseRequest(request);
			Iterator iter = list.iterator();
			int x=0;
			
			StringBuffer img=new StringBuffer();
			String fengmian="";
			String pid="";
			//是否有图片
			
			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				// 来自 TYPE="text" 的表单信息
				if (item.isFormField()) {
					String name = item.getFieldName();
					String value = item.getString();
					if("id".equals(name)){
						logger.info("表单域名为: " + name + "表单域值为: " + value);
						pid=value;
					}

				} else
				// 文件域的所有表单信息
				{
					fileName = getNameWithExtension(item.getName());
					String ext = getExtension(fileName);// 获取扩展名
					logger.info("--> fileName old="+fileName);
					if (isAllowedFileExt(ext)) {
						String fieldname = item.getFieldName();
					
						String nameWithoutExt = isNow.format(new java.util.Date())+x;
						fileName = nameWithoutExt + "." + ext;// 文件改名
						File file = new File(realBaseDir, fileName);
						item.write(file);
						logger.info("--> :  fileName new :"+fileName +" is ok" );
						img.append(fileName+"_");
						
						if("myfile0".equals(fieldname)){
							fengmian=fileName;
						}
						x++;
					} 
				}
			}
			
			if(x>0){
				logger.info(" save database ");
				//保存到数据库
				 
			}
			
			
			
			
			
			out.println("<script type=\"text/javascript\">");
			out.println("alert(' 文件上传成功 !!');");
			out.println("");
			out.println("</script>");
			out.flush();
			out.close();

		} catch (Exception e) {
		 
			  e.printStackTrace();
		}
	}

	/**
	 * 获取扩展名 Made in 2007-11-14上午08:49:11
	 * 
	 * @param fileName
	 * @return
	 * 
	 */
	private String getExtension(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	/*
	 * 获取上传的文件名和扩展名
	 */
	private static String getNameWithExtension(String fileLong) {
		String fileName = "";
		if (fileLong != null) {
			fileLong = fileLong.replace('\\', '/');
			String[] pathParts = fileLong.split("/");
			fileName = pathParts[pathParts.length - 1];// 获得文件名和扩展名
		}
		return fileName;
	}

	/***************************************************************************
	 * 文件类型 判断 Made in 2007-11-15上午06:57:51
	 * 
	 * @param img
	 * @return
	 * 
	 */
	private static boolean isAllowedFileExt(String fileExt) {
		String allowed[] = allowedExtensions.split(",");
		if (fileExt == null)
			return false;
		for (int i = 0; i < allowed.length; i++) {
			if (fileExt.toLowerCase().equals(allowed[i]))
				return true;
		}
		return false;
	}

}
